package com.akcome.apollo.controller;

import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.akcome.apollo.domain.VBmpAcount;
import com.akcome.apollo.dto.UserInfoDto;
import com.akcome.apollo.service.VBmpAcountService;
import com.googlecode.jsonrpc4j.JsonRpcHttpClient;

@RestController
public class ApiController {
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private VBmpAcountService vBmpAcountService;
	
	@Value("${bitcoind.bch.username}")
	private String username;
	
	@Value("${bitcoind.bch.password}")
	private String password;
	
	@Value("${bitcoind.bch.url}")
	private String url;
	
	/**
	 * 同步用户信息
	 * @param updateTime
	 * @return	
	 */
	@RequestMapping("/getUserInfoList")
	public UserInfoDto users(Long updateTime,String coinTypeList,Integer pageIndex,Integer size){
		UserInfoDto userInfoDto = new UserInfoDto();
		List<VBmpAcount> bmpAcounts = vBmpAcountService.getUserInfoList(updateTime,coinTypeList,null==pageIndex?0:pageIndex,null==size?99:size);
		userInfoDto.setData(bmpAcounts);
		return userInfoDto;
	}
	
	/**
	 * 读取blocktemplate高度
	 * @return
	 * @throws Throwable
	 */
	@RequestMapping("/blocktemplate/height")
	public String getblocktemplateHeight(){
		try {
			String cred = Base64Utils.encodeToString((username+":"+password).getBytes());
	    	Map<String, String> headers = new HashMap<String, String>(1);  
	        //身份认证  
	        headers.put("Authorization", "Basic " + cred);
	        JsonRpcHttpClient client = new JsonRpcHttpClient(
	    		    new URL(url),headers);
	        Map<String, Object> result = client.invoke("getblocktemplate",null,Map.class);
	        Object height = result.get("height");
	        logger.warn("BCH getblocktemplate高度:{},previousblockhash:{}",height,result.get("previousblockhash"));
	        return height.toString();
		} catch (Throwable e) {
			e.printStackTrace();
			logger.error("BCH getblocktemplate任务异常",e);
			return null;
		}
	} 
}
